package com.business.exam.service.impl;

import com.business.common.annotation.DataScope;
import com.business.common.core.domain.entity.SysUser;
import com.business.common.utils.SecurityUtils;
import com.business.common.utils.StringUtils;
import com.business.exam.domain.ExamPaperModel;
import com.business.exam.domain.exam.ExamManageModel;
import com.business.exam.domain.exam.ExamManageUserModel;
import com.business.exam.mapper.ExamManageMapper;
import com.business.exam.mapper.ExamPaperMapper;
import com.business.exam.service.IExamManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ExamManageServiceImpl implements IExamManageService {

    @Autowired
    private ExamManageMapper mapper;

    @Autowired
    private ExamPaperMapper examPaperMapper;

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Transactional
    @Override
    public void saveOrEdit(ExamManageModel dto) {
        Date now = new Date();
        dto.setUpdateUser(SecurityUtils.getUserId());
        dto.setUpdateTime(now);
        dto.setCreateUser(SecurityUtils.getUserId());
        List<String> deptIdList = examPaperMapper.getChileDeptIds(SecurityUtils.getDeptId());

        if (dto.getDeptIds() == null || "".equals(dto.getDeptIds())) {
            dto.setDeptIds(StringUtils.toString(SecurityUtils.getDeptId()));
        }

        // 非管理员时
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            dto.setDeptIds(deptIdList.stream().collect(Collectors.joining(",")));
        }
        // 插入数据
        if (dto.getId() == null) {
            // 插入试卷表
            dto.setCreateTime(now);
            dto.setCreateUser(SecurityUtils.getUserId());
            mapper.insertData(dto);
            // ID不为空-时更新数据
        } else {
            mapper.updateData(dto);
        }

        // 更新考试人员信息
        List<String> userIdList = Arrays.asList(dto.getUserIds().split(","));
        // 数据存在时
        if (!CollectionUtils.isEmpty(userIdList)) {
            //  开启批量处理模式 BATCH 、关闭自动提交事务 false
            SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
            ExamManageMapper mapper = sqlSession.getMapper(ExamManageMapper.class);
            userIdList.forEach(data -> {
                ExamManageUserModel model = new ExamManageUserModel();
                model.setUserId(Long.parseLong(data));
                model.setExamManageId(dto.getId());
                // 查看数据是否存在
                ExamManageUserModel existsData = mapper.existsExamUserData(model);
                // 不存在
                if (existsData == null) {
                    mapper.insertExamUserData(model);
                    // 存在更新
                } else {
                    model.setId(existsData.getId());
                    model.setDeleted(0);
                    mapper.updateExamUserData(model);
                }
            });
            long start = System.currentTimeMillis();
            sqlSession.commit();
            long end = System.currentTimeMillis();
            log.info("共计:" + userIdList.size() + "条数据,总耗时：" + (end - start) + "ms");
        }

    }

    @Override
    public List<ExamManageModel> findPage(ExamManageModel dto) {
        dto.setDeptId(SecurityUtils.getDeptId());
        return mapper.selectPageList(dto);
    }

    @Override
    public ExamManageModel findById(ExamManageModel dto) {
        return mapper.selectDataById(dto);
    }

    @Override
    public List<SysUser> findExamUserList(ExamManageUserModel dto) {
        return mapper.selectExamUserList(dto);
    }

    @Override
    public List<SysUser> findSysUserByDeptId(List<String> ids) {
        return mapper.selectExamUserListById(ids);
    }

    @Override
    public void logicDelete(Long id) {
        ExamManageModel dto = new ExamManageModel();
        dto.setId(id);
        dto.setUpdateUser(SecurityUtils.getUserId());
        mapper.deleteById(dto);
    }

}
